package com.fq.core.service.impl;

import com.fq.client.domain.UserDO;
import com.fq.client.service.UserService;
import com.fq.core.dao.UserDAO;
import com.fq.core.util.PasswordUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author jifang
 * @since 15/12/16 下午5:10.
 */
@Service
public class UserServiceImpl implements UserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserDAO dao;

    @Override
    public Integer generate(String name, String password) {
        UserDO user = new UserDO(null, name, PasswordUtil.encodeByMd5(password));
        dao.insertUser(user);
        return user.getId();
    }

    @Override
    public boolean updatePasswordById(Integer id, String oldPassword, String newPassword) {
        try {
            if (this.login(id, oldPassword) != null) {
                dao.updatePasswordById(id, PasswordUtil.encodeByMd5(newPassword));
                return true;
            }
        } catch (Exception e) {
            LOGGER.error("updatePasswordById error: ", e);
        }
        return false;
    }

    @Override
    public void removeUserById(Integer id) {
        dao.deleteUserById(id);
    }


    @Override
    public List<UserDO> getAllUsers() {
        return dao.selectAllUsers();
    }

    @Override
    public Integer login(Integer id, String password) {
        UserDO user = dao.selectUserById(id);
        if (user != null && PasswordUtil.checkEqual(password, user.getPassword())) {
            return user.getId();
        }
        return null;
    }
}
